<template>
  <div>
    <div class="middle-top align-center">
      <img :src="authorInfo.avatar" width="50" height="50" alt="avatar" />
      <div class="description">
        <p class="name">{{ authorInfo.nikname }}</p>
        <p class="desc">{{ authorInfo.signature }}</p>
        <p class="startTime">博客开始时间: {{ authorInfo.createdAt | parseTimeTz }}</p>
      </div>
      <div class="btns" v-if="isLogin">
        <el-button class="btn" size="small" circle title="编辑资料" @click="dialogFormVisible1 = true">
          <i class="iconfont icon-bianjiziliao"></i>
        </el-button>
        <el-button class="btn" size="small" circle title="修改密码" @click="dialogFormVisible2 = true">
          <i class="iconfont icon-icon_xiugaimima"></i>
        </el-button>
      </div>
      <div class="btns" v-else>
        <el-button class="btn" size="small" type="primary">关注</el-button>
      </div>
    </div>
    <!-- 修改基本信息弹窗 -->
    <el-dialog title="修改基本信息" :visible.sync="dialogFormVisible1">
      <el-form :model="userInfoForm" :rules="rules" ref="userInfoForm">
        <el-form-item label="昵称" label-width="100px" prop="nikname">
          <el-input v-model="userInfoForm.nikname"></el-input>
        </el-form-item>
        <el-form-item label="用户头像" label-width="100px" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="action"
            :show-file-list="false"
            :http-request="addAvatar"
            :before-upload="beforeUpload"
          >
            <img
              v-if="userInfoForm.avatar"
              :src="userInfoForm.avatar"
              width="50"
              height="50"
              alt="avatar"
              class="avatar"
            />
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="邮箱" label-width="100px" prop="email">
          <el-input v-model="userInfoForm.email"></el-input>
        </el-form-item>
        <el-form-item label="简介" label-width="100px" prop="signature">
          <el-input v-model="userInfoForm.signature"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改密码弹窗 -->
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible2">
      <el-form :model="pwdForm" :rules="pwdRules" ref="pwdForm">
        <el-form-item label="旧密码" label-width="100px" prop="oldPassword">
          <el-input type="password" v-model="pwdForm.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" label-width="100px" prop="newPassword">
          <el-input type="password" v-model="pwdForm.newPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitPwd">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { uploadAvatar, updateAuthorInfo, changePwd } from '@/api/user'
import { isUserLoggedIn } from '@/utils/auth'
import { validPassword } from '@/utils/validate'
import { encrypt } from '@/utils/encrypt'

export default {
  name: 'AuthorInfo',
  props: {
    authorInfo: {
      type: Object,
      default: () => ({
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        nikname: 'admin',
        signature: '这家伙很懒，什么都没留下',
        createdAt: '2019-01-01T00:00:00.000Z'
      })
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('密码8-16个字符，至少1个字母，1个数字'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      formData: {},
      isLogin: isUserLoggedIn(),
      userInfoForm: {
        nikname: '',
        email: '',
        signature: '',
        avatar: ''
      },
      rules: {
        nikname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', trigger: 'blur', message: '邮箱格式不正确' }
        ],
        signature: [{ required: true, message: '请输入简介', trigger: 'blur' }]
      },
      pwdForm: {
        oldPassword: '',
        newPassword: ''
      },
      pwdRules: {
        oldPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        newPassword: [{ required: true, trigger: 'blur', validator: validatePassword }]
      }
    }
  },
  watch: {
    authorInfo(newValue) {
      this.userInfoForm = {
        nikname: newValue.nikname,
        email: newValue.email,
        signature: newValue.signature,
        avatar: newValue.avatar
      }
    }
  },
  methods: {
    // 上传头像
    async addAvatar() {
      const formData = this.formData
      try {
        this.userInfoForm.avatar = ''
        var result = await uploadAvatar(formData)
        console.log('result: ', result)
        this.userInfoForm.avatar = result.data.imgUrl
        console.log('this.userInfoForm.avatar: ', this.userInfoForm.avatar)
        this.$message({
          type: 'success',
          message: '头像添加成功',
          offset: 80
        })
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 上传文件之前钩子
    beforeUpload(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      const typeInfo = ['jpg', 'png', 'jpeg']
      if (!typeInfo.includes(type)) {
        this.$message({
          type: 'error',
          message: '只支持jpg,png,jpeg文件格式！',
          offset: 80
        })
        return false
      }
      if (file.size / 1024 > 2048) {
        this.$message({ type: 'error', message: '图片不能大于2M！', offset: 80 })
        return false
      }
      const formData = new FormData()
      formData.append('files', file)
      console.log('formData: ', formData)
      this.formData = formData
    },
    // 提交表单
    submitForm() {
      this.$refs.userInfoForm.validate(async valid => {
        if (valid) {
          try {
            const { nikname, email, signature, avatar } = this.userInfoForm
            const res = await updateAuthorInfo({ _id: this.authorInfo._id, nikname, email, signature, avatar })
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '修改成功',
                offset: 80
              })
              this.dialogFormVisible1 = false
              this.$emit('updateAuthorInfo')
            }
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    // 取消弹窗
    cancel() {
      this.dialogFormVisible1 = false
      this.$refs.userInfoForm.resetFields()
    },
    // 修改密码
    submitPwd() {
      this.$refs.pwdForm.validate(async valid => {
        if (valid) {
          try {
            const { oldPassword, newPassword } = this.pwdForm
            console.log(111)
            const encryptNewPwd = await encrypt(newPassword)
            console.log(222)
            const encryptOldPwd = await encrypt(oldPassword)
            const res = await changePwd({
              oldPassword: encryptOldPwd,
              newPassword: encryptNewPwd,
              _id: this.authorInfo._id
            })
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '密码修改成功,请重新登录',
                offset: 80
              })
              this.dialogFormVisible2 = false
            }
          } catch (error) {
            console.log(error)
          }
        } else {
          this.$message({
            type: 'error',
            message: '请检查输入是否正确',
            offset: 80
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.middle-top {
  padding: 20px;
  background-color: white;
  .description {
    margin-left: 30px;
  }
  .name {
    font-size: 20px;
    font-weight: bold;
  }
  .desc {
    font-size: 14px;
    color: #999;
    margin-top: 5px;
  }
  .startTime {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }
  .btns {
    margin-left: 200px;
  }
  .avatar {
    margin-right: 20px;
  }
}
</style>
